/**
 * 出入记录模块
 * @author xiaoxujs
 */

import { FC, useCallback, useEffect, useState } from "react";
import { ChurujiluBox } from "./style";
import { Button, ConfigProvider, GetProps, Input, message, Table, TableProps, Tooltip, Upload, UploadProps } from "antd";
import { ISelectList, TablePaginationPosition } from "../../../../../type/antd";
import { IBaseEntryVoucherEntryRecord, IBaseEntryVoucherEntryRecordParams } from "../../../../../type/Jinchu";
import { getBaseEntryVoucherDownloadTemplateUrl, postBaseEntryVoucherEntryExport, postBaseEntryVoucherEntryRecord } from "../../../api";
import { IFenye } from "../../../../../type/commit";
import { basicIp } from "../../../../../api/http";
import ImageModule from "../ImageModule";
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";
import Tuojiluru from '../Tuojiluru'
import { gethandleTemplateDownload, gethandleTemplateDownloadPost } from "../../../../../assets/fun/fileDownloadFun";
import { handleUploadFileRestrictions } from "../../../../../assets/fun/Antd/file";

type SearchProps = GetProps<typeof Input.Search>;

const { Search } = Input;

const Churujilu: FC<{
    carColorList: ISelectList[]
}> = ({
    carColorList
}) => {

        const contentValue: TablePaginationPosition = "bottomCenter"; //位置
        // const [form] = Form.useForm<IBaseEntryVoucherPageForm>();
        // const { validateFields, resetFields } = form;

        const [imageShow, setImageShow] = useState(false); //图片显示
        const [imageUrl, setImageUrl] = useState<string>(); // 图片地址

        // const [carColorList, setCarColorList] = useState<ISelectList[]>([]); // 车辆类型字典项
        const [listData, setListData] = useState<IBaseEntryVoucherEntryRecord[]>([]);
        const [paging, setPaging] = useState({
            currentPage: 1,
            pageSize: 3,
        });
        const [total, setTotal] = useState(0);
        const [tableLoading, setTableLoading] = useState(false); //tableLoading
        const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);//列表选择数据
        const [searchValue, setSearchValue] = useState<string>(''); //关键字
        const [tuojiluruShow, setTuojiluruShow] = useState(false); //  脱机录入
        const [rukuangjiluLoading, setRukuangjiluLoading] = useState(false); // 导出列表loading
        const [mobanxiazaiLoading, setMobanxiazaiLoading] = useState(false); // 模板下载loading

        const listFun = useCallback(async (params: IBaseEntryVoucherEntryRecordParams) => {
            setTableLoading(true);
            const { code, msg, data } = (await postBaseEntryVoucherEntryRecord(
                params
            )) as IFenye<IBaseEntryVoucherEntryRecord>;
            if (code === 20000) {
                setListData(data.records);
                setPaging({
                    currentPage: params.currentPage,
                    pageSize: params.pageSize,
                })
                setTotal(data.total);
                setTableLoading(false);
            } else {
                message.error(msg);
            }
        }, []);

        useEffect(() => {
            const params = {
                currentPage: 1,
                pageSize: 3
            }
            listFun(params);
        }, [listFun])



        const onSearch: SearchProps['onSearch'] = (value, _e, info) => {
            setSearchValue(value)
            const params = {
                currentPage: 1,
                pageSize: 3,
                param: value
            }
            listFun(params)
        };
        const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
            setSelectedRowKeys(newSelectedRowKeys);
        };
        const rowSelection = {
            selectedRowKeys,
            onChange: onSelectChange,
        }
        // 照片弹窗 - 回调函数 - 清除图片地址 关闭弹窗
        const handleCallback = () => {
            setImageUrl(undefined);
            setImageShow(false);
        }
        // 脱机录入 - 刷新列表数据、关闭弹窗
        const handleAddCallback = () => {
            const params = {
                currentPage: 1,
                pageSize: 6,
            }
            listFun(params);
            setTuojiluruShow(false);
        }
        // 文件拖拽上传
        const dianjiProps: UploadProps = {
            name: "file", //上传名字
            action: basicIp + "/base/entryVoucher/entryImport", // 上传地址
            method: "put", // 上传方法
            maxCount: 1, // 页面显示最多条数
            headers: {
                satoken: sessionStorage.getItem("token")!, // 请求头
                checkType: "ck-token-auth",
            },
            beforeUpload: (file) => handleUploadFileRestrictions(file, { size: 100 }),
            onChange(info) {
                let newFileList = [...info.fileList];
                newFileList.map((file) => {
                    if (file.response) {
                        if (file.response.code === 20000) {
                            const params = {
                                currentPage: 1,
                                pageSize: 3,
                            }
                            listFun(params)
                            message.success('导入成功')
                            file.status = "done";
                        } else {
                            message.error(file.response.msg)
                            file.status = "error";
                        }
                    }
                    return file;
                });
            },
        };
        // 列表导出
        const handleExportList = () => {
            console.log()
            if (selectedRowKeys.length > 0) {
                setRukuangjiluLoading(true);
                gethandleTemplateDownloadPost(postBaseEntryVoucherEntryExport, {
                    ids: selectedRowKeys
                }, 'xlsx', 'arraybuffer', () => {
                    setRukuangjiluLoading(false);
                })
            } else {
                message.error('请先选择入矿记录')
            }

        }
        const pagination = {
            //分页
            position: [contentValue],
            //是否可以改变pagesize//
            showSizeChanger: true,
            //是否可以快速跳转到某页
            // showQuickJumper: true,
            //展示一共有多少条数据//
            showTotal: () => `共${total}条`,
            //每页条数
            pageSize: paging.pageSize,
            //当前页数
            current: paging.currentPage,
            //数据总数
            total: total,
            //页码改变的回调，参数是改变后的页码及每页条数
            onChange: (current: number, pageSize: number) => {
                const params = {
                    currentPage: current,
                    pageSize: pageSize,
                    param: searchValue
                }
                listFun(params)
            },
        };
        const columns: TableProps<IBaseEntryVoucherEntryRecord>['columns'] = [
            {
                title: '入矿记录编号',
                align: 'center',
                dataIndex: 'entryNum',
            },
            {
                title: '车牌号',
                dataIndex: 'licensePlate',
                align: 'center',
            },
            {
                title: '司机电话',
                dataIndex: 'driverPhone',
                align: 'center',
            },
            {
                title: '实际入矿时间',
                dataIndex: 'actualEntryTime',
                align: 'center',
            },
            {
                title: '入矿说明情况',
                dataIndex: 'enterMessage',
                align: 'center',
                render: (text) => 
                    text && text.length > 4 ? (
                        <Tooltip title={text}>
                            {text.slice(0, 4) + '...'}
                        </Tooltip>
                    ) : (
                        text
                    ),
            },
            {
                title: '照片',
                dataIndex: 'address',
                align: "center",
                render: (_, record) => <>
                    <Button 
                        type="link" 
                        onClick={() => {
                            setImageUrl(basicIp + record.entryPhoto.url);
                            setImageShow(true);
                        }}
                    >
                        {record.entryPhoto.fileName?.length > 4 ? (
                            <Tooltip title={record.entryPhoto.fileName}>
                                {record.entryPhoto.fileName.slice(0, 4) + '...'}
                            </Tooltip>
                        ) : (
                            record.entryPhoto.fileName
                        )}
                    </Button>
                </>
            },
        ];
        return <ChurujiluBox>
            <div className="gongneng_title">
                <div className="title">入厂记录</div>
                <div className="button_box">
                    <Tooltip title="当系统发生故障无法自动识别车辆时，由人工脱机录入系统。">
                        <Button 
                            style={{ marginLeft: '2rem' }} 
                            icon={<span className="iconfont">&#xe619;</span>} 
                            type="primary"
                            onClick={() => setTuojiluruShow(true)}
                        >脱机录入</Button>
                    </Tooltip>
                    <Button style={{ marginLeft: '2rem' }} loading={mobanxiazaiLoading} icon={<span className="iconfont">&#xe60e;</span>} onClick={() => gethandleTemplateDownload(getBaseEntryVoucherDownloadTemplateUrl, {
                        type: '1'
                    }, 'xlsx', 'arraybuffer', () => {
                        setMobanxiazaiLoading(false);
                    })}>模板下载</Button>
                    <Upload {...dianjiProps}>
                        <Button style={{ marginLeft: '2rem' }} icon={<span className="iconfont">&#xe65f;</span>}>批量导入</Button>
                    </Upload>

                    <Button 
                        onClick={handleExportList} 
                        style={{ marginLeft: '2rem' }} 
                        loading={rukuangjiluLoading} 
                        icon={<span className="iconfont">&#xe645;</span>}
                        
                    >导出列表</Button>
                </div>
            </div>
            <Search placeholder="请搜索关键字" onSearch={onSearch} style={{ width: '20rem' }} />
            <ConfigProvider theme={{
                components: {
                    Table: {
                        headerColor: '#8B9BAC',
                        cellFontSize: useWindowFontSize(14),
                        cellPaddingBlock: 7
                    }
                }
            }}>    <Table<IBaseEntryVoucherEntryRecord>
                    pagination={pagination}
                    rowKey='id'
                    rowSelection={{ type: 'checkbox', ...rowSelection }}
                    columns={columns}
                    dataSource={listData}
                    loading={tableLoading}
                /></ConfigProvider>

            <ImageModule visible={imageShow} handleCallback={handleCallback} src={imageUrl} />
            <Tuojiluru open={tuojiluruShow} carColorList={carColorList} handleCallback={handleAddCallback} />
        </ChurujiluBox>
    }

export default Churujilu;